﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace rftc
{
    internal class RSSReader
    {
        private string sourceUrl;
        private XmlDocument document=null;

        /// <summary>
        /// 初始化RSSReader类
        /// </summary>
        /// <param name="SourceUrl">RSS源的地址</param>
        internal RSSReader(string SourceUrl)
        {
            sourceUrl = SourceUrl;//初始化RSS源地址
            InitializeXmlDocument();//初始化XML文档
        }

        /// <summary>
        /// 获取RSS源的XML文件并用此文件初始化XML文档
        /// </summary>
        /// <returns>返回-1表示文档格式不是RSS源的格式，0表示成功执行</returns>
        private int InitializeXmlDocument()
        {
            document = new XmlDocument();
            WebRequest request = HttpWebRequest.Create(sourceUrl);
            request.Method = "GET";
            Stream s=request.GetResponse().GetResponseStream();
            document.Load(s);
            if (document.SelectSingleNode("/rss") == null)//简单判断是否为规范的RSS源的XML文档
            {
                document = null;
                return -1;//不规范则返回错误代码
            }
            else
            {
                return 0;
            }
        }


        /// <summary>
        /// 获取RSS源中的文章链接
        /// </summary>
        /// <returns>返回文章链接的泛型列表，返回null表示读取错误</returns>
        internal List<String> GetArticleLinks()
        {
            if (document != null)//判断是否是正确的RSS文档
            {
                List<String> linklist = new List<string>();
                XmlNodeList nodelist = document.SelectNodes("//item/link");//选择link元素
                foreach (XmlNode node in nodelist)
                {
                    linklist.Add(node.InnerText);
                }
                return linklist;
            }
            else
            {
                return null;
            }
        }
    }
}
